<template>
  <view class="image-uploader">
    <!-- 图片网格显示 -->
    <view class="image-grid">
      <view 
        v-for="(image, index) in images" 
        :key="index" 
        class="image-item"
      >
        <view class="image-preview" @click="previewImage(index)">
          <image 
            :src="image" 
            mode="aspectFill" 
            class="image"
          />
          <view 
            class="delete-btn" 
            @click.stop="deleteImage(index)"
          >
            <IconFont name="close" color="white" size="12" />
          </view>
        </view>
      </view>
      
      <!-- 添加图片按钮 -->
      <view 
        v-if="images.length < maxCount" 
        class="add-image-btn" 
        @click="selectImages"
      >
        <IconFont name="plus" color="#999" size="24" />
        <text class="add-text">添加图片</text>
      </view>
    </view>
    
    <!-- 图片数量提示 -->
    <view class="image-count-tip">
      <text class="tip-text">{{ images.length }}/{{ maxCount }} 张图片</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import Taro from '@tarojs/taro'
import { IconFont } from '@nutui/icons-vue-taro'
import { selectAndUploadImages, previewImages, confirmDeleteImage } from '@/utils/imageUpload'

interface Props {
  modelValue: string[]
  maxCount?: number
  disabled?: boolean
}

interface Emits {
  (e: 'update:modelValue', value: string[]): void
  (e: 'tap'): void
}

const props = withDefaults(defineProps<Props>(), {
  maxCount: 9,
  disabled: false
})

const emit = defineEmits<Emits>()

const images = ref<string[]>([])

// 监听外部值变化
watch(() => props.modelValue, (newValue) => {
  const newImages = [...(newValue || [])]
  // 只有当值真正不同时才更新，避免循环
  if (JSON.stringify(images.value) !== JSON.stringify(newImages)) {
    images.value = newImages
  }
}, { immediate: true })

// 监听内部值变化，同步到外部
watch(images, (newValue) => {
  const newImages = [...newValue]
  // 只有当值真正不同时才触发更新，避免循环
  if (JSON.stringify(props.modelValue) !== JSON.stringify(newImages)) {
    emit('update:modelValue', newImages)
  }
}, { deep: true })

// 选择图片
async function selectImages() {
  if (props.disabled) return
  
  try {
    const remainingSlots = props.maxCount - images.value.length
    if (remainingSlots <= 0) {
      Taro.showToast({
        title: `最多只能上传${props.maxCount}张图片`,
        icon: 'none'
      })
      return
    }

    const results = await selectAndUploadImages({
      maxCount: remainingSlots
    })

    // 添加成功上传的图片
    results.forEach((result) => {
      if (result.success && result.url) {
        images.value.push(result.url)
      }
    })

    if (results.length > 0) {
      Taro.showToast({
        title: `成功上传${results.filter(r => r.success).length}张图片`,
        icon: 'success'
      })
    }
  } catch (error) {
    console.error('选择图片失败:', error)
    Taro.showToast({
      title: '选择图片失败',
      icon: 'error'
    })
  }
}

// 预览图片
function previewImage(index: number) {
  previewImages(images.value, index)
}

// 删除图片
function deleteImage(index: number) {
  confirmDeleteImage(() => {
    images.value.splice(index, 1)
  })
}
</script>

<style scoped lang="scss">
.image-uploader {
  width: 100%;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12rpx;
  margin-bottom: 12rpx;
}

.image-item {
  position: relative;
}

.image-preview {
  position: relative;
  width: 100%;
  height: 200rpx;
  border-radius: 8rpx;
  overflow: hidden;
  border: 2rpx solid #e5e5e5;
}

.image {
  width: 100%;
  height: 100%;
}

.delete-btn {
  position: absolute;
  top: -8rpx;
  right: -8rpx;
  width: 32rpx;
  height: 32rpx;
  background-color: #ef4444;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 10;
}

.delete-btn:hover {
  background-color: #dc2626;
}

.add-image-btn {
  width: 100%;
  height: 200rpx;
  border: 2rpx dashed #d1d5db;
  border-radius: 8rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f9fafb;
  cursor: pointer;
  transition: all 0.2s ease;
}

.add-image-btn:hover {
  border-color: #27c530;
  background-color: #f0f9f0;
}

.add-image-btn:active {
  transform: scale(0.98);
}

.add-text {
  font-size: 24rpx;
  color: #6b7280;
  margin-top: 8rpx;
}

.image-count-tip {
  text-align: center;
}

.tip-text {
  font-size: 22rpx;
  color: #9ca3af;
}
</style>